<template>
  <div class="page">
    <el-card>
      <el-row class="filter-container">
        <el-input
          placeholder="凭证编号"
          v-model="query.pzh"
          size="small"
          style="width: 150px;"
          class="filter-item"
        />
        <el-select v-model="query.zclb" style="width: 100px;" clearable
                   @change="handleMcChange" class="filter-item" placeholder="资产类别"
        >
          <el-option
            v-for="item in zcDic"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
        <el-select v-model="query.mc" style="width: 100px;" clearable
                   class="filter-item" placeholder="名称"
        >
          <el-option
            v-for="item in zclbDic"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <el-select v-model="query.cfd" style="width: 120px;" clearable
                   @change="handleCfdChange" class="filter-item" placeholder="存放地点"
        >
          <el-option
            v-for="item in cfDic"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
        <el-select v-model="query.fjh" style="width: 100px;" clearable
                   class="filter-item" placeholder="房间号"
        >
          <el-option
            v-for="item in fjhDic"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          />
        </el-select>
        <el-input v-model="query.krxm" placeholder="客人姓名"
                  style="width: 150px;" class="filter-item"
        />
        <el-select v-model="query.zt" style="width: 100px;" clearable
                   class="filter-item" placeholder="状态"
        >
          <el-option
            v-for="(label, key) in ztDic"
            :key="key"
            :label="label"
            :value="key"
          />
        </el-select>
        <el-input
          placeholder="已使用年限"
          v-model="query.synx"
          size="small"
          style="width: 120px;"
          class="filter-item"
        />
        <el-button
          type="primary"
          size="small"
          class="filter-item"
          icon="el-icon-search"
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button
          type="primary"
          size="small"
          class="filter-item"
          icon="el-icon-plus"
          @click="handleAdd"
          v-if="role === 'dandang'"
        >
          新增
        </el-button>
        <el-dropdown @command="handlePrint" szie="small" class="filter-item">
          <el-button type="primary" size="small">
            导出Excel
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">设备登记表</el-dropdown-item>
            <el-dropdown-item command="b">列表导出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-row>
      <el-row>
        <el-table
          :data="tableData"
          border
          highlight-current-row
          fit
          :height="maxHeight"
          style="width: 100%"
          header-cell-class-name="table-header-custom"
          v-loading="tableLoading"
          size="small"
          ref="table"
          @row-dblclick="handleDblclick"
          @row-click="handleRowClick"
          :row-style="rowStyle"
          @cell-click="handleCellClick"
        >
          <el-table-column label="凭证编号" prop="pzh" width="110" />
          <el-table-column label="名称" prop="mc">
            <template slot-scope="{ row }">
              {{
                row.mc && zcDic.find(item => item.code === row.zclb).dicDetails
                  .find(item => item.key === row.mc).label
              }}
            </template>
          </el-table-column>
          <el-table-column label="资产类别" prop="zclb">
            <template slot-scope="{ row }">
              {{ row.zclb && zcDic.find(item => item.code === row.zclb).name }}
            </template>
          </el-table-column>
          <el-table-column label="品牌" prop="pp" width="100" />
          <el-table-column label="规格型号" prop="ggxh" width="100" />
          <el-table-column label="出厂日期" prop="ccrq" width="100" />
          <el-table-column label="购买日期" prop="gmrq" width="100" />
          <el-table-column label="已使用年限" prop="synx" width="100" />
          <el-table-column label="数量" prop="sl" />
          <el-table-column label="客人公司" prop="krgs" />
          <el-table-column label="客人姓名" prop="krxm" />
          <el-table-column label="房租" prop="fz" />
          <el-table-column label="存放地点" prop="cfd" width="100">
            <template slot-scope="{ row }">
              {{ row.cfd && cfDic.find(item => item.code === row.cfd).name }}
            </template>
          </el-table-column>
          <el-table-column label="房间号" prop="fjh">
            <template slot-scope="{ row }">
              {{
                row.fjh && cfDic.find(item => item.code === row.cfd).dicDetails
                  .find(item => item.key === row.fjh).label
              }}
            </template>
          </el-table-column>
          <el-table-column label="合同开始时间" prop="htksrq" width="100" />
          <el-table-column label="合同结束时间" prop="htjsrq" width="100" />
          <el-table-column label="营业部负责人" prop="yybfzr" width="100">
            <template slot-scope="{ row }">
              {{
                row.yybfzr &&
                  userDic.find(item => item.username === row.yybfzr).person.personName
              }}
            </template>
          </el-table-column>
          <el-table-column label="单位负责人" prop="dwfzr" width="100">
            <template slot-scope="{ row }">
              {{ row.dwfzr && userDic.find(item => item.username === row.dwfzr).person.personName }}
            </template>
          </el-table-column>
          <el-table-column label="经办人" prop="jbr">
            <template slot-scope="{ row }">
              {{ row.jbr && userDic.find(item => item.username === row.jbr).person.personName }}
            </template>
          </el-table-column>
          <el-table-column label="制单时间" prop="zdrq" width="100" />
          <el-table-column label="制单人" prop="zdr" width="100">
            <template slot-scope="{ row }">
              {{ row.zdr && userDic.find(item => item.username === row.zdr).person.personName }}
            </template>
          </el-table-column>
          <el-table-column label="第二担当" prop="dedd" width="100">
            <template slot-scope="{ row }">
              {{ row.dedd && userDic.find(item => item.username === row.dedd).person.personName }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="zt">
            <template slot-scope="{ row }">
              {{ ztDic[row.zt] }}
            </template>
          </el-table-column>
          <el-table-column label="状态日期" prop="ztrq" width="100" />
          <el-table-column label="备注" prop="bz" width="200" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template slot-scope="scope">
              <template v-if="role === 'dandang' && !scope.row.auditFlag">
                <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="handleRemove(scope.row)">删除</el-button>
              </template>
              <template v-if="role === 'dandang'
                && !['04', '05', '03', '01'].includes(scope.row.zt)"
              >
                <el-button type="primary" size="mini"
                           @click="handleUpdateZt(scope.row, '05')"
                >
                  报废
                </el-button>
                <el-dropdown @command="command => handleCommand(command, scope.row)"
                             szie="small" style="margin-left: 10px;"
                >
                  <el-button type="primary" size="mini">
                    转移
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="a">库房</el-dropdown-item>
                    <el-dropdown-item command="b">龙宝</el-dropdown-item>
                    <el-dropdown-item command="c">中介</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
              <el-button type="primary" size="mini"
                         @click="handleEdit(scope.row)"
                         v-if="role === 'zhixing' && scope.row.enableAudit"
              >
                办理
              </el-button>
              <template v-if="['buzhang', 'fuzong'].includes(role) && scope.row.enableAudit">
                <el-button type="primary" size="mini"
                           @click="handleAudit(scope.row, '1')"
                >
                  审核
                </el-button>
                <el-button type="primary" size="mini"
                           @click="handleAudit(scope.row, '2')"
                >
                  驳回
                </el-button>
              </template>
              <template v-if="['fuzong'].includes(role) && scope.row.zt === '05'">
                <el-button type="primary" size="mini"
                           @click="handleAudit(scope.row, '3')"
                >
                  报废审核
                </el-button>
                <el-button type="primary" size="mini"
                           @click="handleAudit(scope.row, '4')"
                >
                  驳回
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.page"
          :page-size="page.pageSize"
          :page-sizes="page.pageSizes"
          :total="page.total"
          background
          layout="total, sizes, prev, pager, next, jumper, slot"
        >
          <el-button size="mini" icon="el-icon-refresh" @click="refresh" plain>刷新</el-button>
        </el-pagination>
      </el-row>
    </el-card>
    <el-dialog
      title="填写驳回原因"
      :visible.sync="rejectFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="40%"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        size="small"
        label-width="80px"
        style="width: 80%;"
      >
        <el-row :gutter="10">
          <el-form-item label="驳回原因" prop="reason">
            <el-input type="textarea" :rows="3" v-model="form.reason" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">驳 回</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="流程进度"
      width="50%"
      custom-class="custom-card"
      :visible.sync="processVisible"
      :close-on-click-modal="false"
    >
      <ProcessSteps :approval-info="selectedRow.approvalinfos" :user-dic="userDic" />
    </el-dialog>
  </div>
</template>

<script>
import mixins from '@/utils/mixins/commonMixin';
import {
  getList, remove, updateZt, exportExcel, exportExcelAll,
} from '@/api/assets-zj';
import { getList as getDicList } from '@/api/dic';
import { ztDic } from '@/utils/dic';
import { getUserList } from '@/api/user';
import { updateAudit } from '@/api/approvalinfo';
import ProcessSteps from '@/components/process/progress-steps';
import { getProcess } from '@/api/process';
import { save as updateKc } from '@/api/assets-gl';
import { save as updateBf, getAssetsBf } from '@/api/assets-bf';

export default {
  name: 'AssetsZj',
  mixins: [mixins],
  components: {
    ProcessSteps,
  },
  data() {
    return {
      query: {
        pzh: '',
        zclb: '',
        mc: '',
        cfd: '',
        fjh: '',
        krxm: '',
        zt: '',
        synx: '',
      },
      tableData: [],
      page: {
        page: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50],
      },
      tableLoading: false,
      otherHeight: 165,
      zcDic: [],
      cfDic: [],
      zclbDic: [],
      fjhDic: [],
      userDic: [],
      ztDic,
      rejectFormVisible: false,
      form: {
        reason: '',
      },
      rules: {
        reason: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      selectedRow: {},
      processVisible: false,
      process: [],
    };
  },
  computed: {
    role() {
      if (this.$store.state.user.role) {
        return this.$store.state.user.role.roleCode;
      }
      return '';
    },
  },
  async mounted() {
    const [zc, cf, user, process] = await Promise.all([
      this.getZcDic(), this.getCfDic(), this.getUserDic(), this.getProcess(),
    ]);
    this.zcDic = zc.data;
    this.cfDic = cf.data;
    this.userDic = user.data;
    this.process = process.data;
    this.handleSearch();
  },
  methods: {
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.page.page = val;
      this.getTableData();
    },
    getTableData() {
      const params = {
        page: this.page.page,
        pageSize: this.page.pageSize,
        ...this.query,
      };
      this.tableLoading = true;
      getList(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          const index = this.process.findIndex(item => item.role === this.role);
          this.tableData = res.data.map(item => {
            if (item.approvalinfos && item.approvalinfos.length > 0
              && item.approvalinfos[0].spjs !== this.role && item.approvalinfos[0].spzt === '1') {
              item.auditFlag = true;
            }
            if (this.role !== this.process[0].role && item.approvalinfos
              && item.approvalinfos.length > 0
              && item.approvalinfos[0].spjs === this.process[index - 1].role) {
              item.enableAudit = true;
            }
            return item;
          });
          this.page.total = res.total;
        } else {
          this.tableData = [];
          this.page.total = 0;
        }
      });
    },
    handleSearch() {
      this.page.page = 1;
      this.getTableData();
    },
    handleAdd() {
      this.$router.push({ path: '/assets/assetsZjEdit' });
    },
    handleEdit(val) {
      this.$router.push({
        path: '/assets/assetsZjEdit',
        query: {
          pzh: val.pzh,
        },
      });
    },
    refresh() {
      this.getTableData();
    },
    handleRemove(row) {
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        if (row.kcid) {
          const params = {
            id: row.kcid,
            zt: '1',
            ztrq: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
          };
          const res = await updateKc(params);
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
        }
        remove({ pzh: row.pzh }).then(res => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.refresh();
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => {});
    },
    getZcDic() {
      const params = {
        page: 1,
        pageSize: 10000,
        description: '资产列表',
      };
      return getDicList(params);
    },
    getCfDic() {
      const params = {
        page: 1,
        pageSize: 10000,
        description: '存放地点-中介',
      };
      return getDicList(params);
    },
    getUserDic() {
      const params = {
        page: 1,
        pageSize: 10000,
      };
      return getUserList(params);
    },
    handleUpdateZt(row, zt) {
      if (zt === '04') {
        this.$confirm('是否确定报废？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          updateZt({ pzh: row.pzh, zt }).then(res => {
            if (res.code === 200) {
              this.$message.success('操作成功');
              this.refresh();
            }
          });
        }).catch(() => {});
      } else if (zt === '03') {
        this.$prompt('请添加转移说明', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          updateZt({ pzh: row.pzh, zt, sm: value }).then(res => {
            if (res.code === 200) {
              const params = {
                id: row.kcid,
                zt: '1',
                ztrq: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
              };
              updateKc(params).then(response => {
                if (response.code === 200) {
                  this.$message.success('操作成功');
                  this.refresh();
                } else {
                  this.$message.error('操作失败');
                }
              });
            } else {
              this.$message.error('操作失败');
            }
          });
        }).catch(() => {});
      } else if (zt === '05') {
        this.$confirm('是否确定报废？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          updateZt({ pzh: row.pzh, zt }).then(res => {
            if (res.code === 200) {
              this.$message.success('操作成功');
              this.refresh();
            } else {
              this.$message.error('操作失败');
            }
          });
        }).catch(() => {});
      } else {
        updateZt({ pzh: row.pzh, zt }).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.refresh();
          }
        });
      }
    },
    handleCancel() {
      this.rejectFormVisible = false;
    },
    handleSave() {
      const data = {
        pzh: this.selectedRow.pzh,
        spsm: this.form.reason,
        spzt: '2',
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateAudit(data).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '驳回成功',
              });
              this.rejectFormVisible = false;
              this.getTableData();
            } else {
              this.$message({
                type: 'error',
                message: '驳回失败',
              });
            }
          });
        }
      });
    },
    handleAudit(row, flag) {
      if (flag === '1') {
        const data = {
          pzh: row.pzh,
          spzt: '1',
        };
        updateAudit(data).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '审核成功',
            });
            this.getTableData();
          } else {
            this.$message({
              type: 'error',
              message: '审核失败',
            });
          }
        });
      } else if (flag === '2') {
        this.rejectFormVisible = true;
        this.selectedRow = row;
      } else if (flag === '3') {
        this.handleUpdateZt(row, '04');
        this.handleUpdateStatus(row);
      } else if (flag === '4') {
        this.$prompt('请填写驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          updateBf({ type: 2, pzh: row.pzh, bhyy: value }).then(res => {
            if (res.code === 200) {
              this.handleUpdateZt(row, '02');
            }
          });
        }).catch(() => {});
      }
    },
    handlePrint(command) {
      if (command === 'a') {
        if (this.$lodash.isEmpty(this.selectedRow)) {
          this.$message.warning('请先选择需要导出的记录');
          return;
        }
        exportExcel({
          cfd: this.selectedRow.cfd,
          fjh: this.selectedRow.fjh,
        }).then(res => {
          const content = res;
          const fileName = '中介服务物品领用申请表.xlsx';
          this.download(content, fileName);
        });
      } else {
        exportExcelAll(this.query).then(res => {
          const content = res;
          const fileName = '中介列表.xlsx';
          this.download(content, fileName);
        });
      }
    },
    download(content, fileName) {
      const blob = new Blob([content]);
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, fileName);
      }
    },
    handleDblclick(row) {
      // TODO 流程展现
      this.selectedRow = row;
      this.$nextTick(() => {
        this.processVisible = true;
      });
    },
    handleRowClick(row) {
      this.selectedRow = row;
    },
    getProcess() {
      return getProcess();
    },
    handleMcChange(val) {
      this.query.mc = '';
      this.zclbDic = this.zcDic.find(item => item.code === val).dicDetails;
    },
    handleCfdChange(val) {
      this.query.fjh = '';
      this.fjhDic = this.cfDic.find(item => item.code === val).dicDetails;
    },
    rowStyle(val) {
      const current = this.$dayjs();
      const htjsrq = this.$dayjs(val.row.htjsrq);
      const days = this.$dayjs.duration(htjsrq.diff(current)).asDays();
      if (days <= 30 && days >= 0 && val.row.zt === '02') {
        return { backgroundColor: '#FFF0F0', color: 'black' };
      }
      return { color: 'black' };
    },
    handleCommand(command, row) {
      if (command === 'a') {
        this.handleUpdateZt(row, '03');
      }
      if (command === 'b') {
        this.$router.push({
          path: '/assets/assetsLbEdit',
          query: {
            type: 'zy',
            ly: 'zj',
            data: row,
          },
        });
      }
      if (command === 'c') {
        this.$router.push({
          path: '/assets/assetsZjEdit',
          query: {
            type: 'zy',
            data: row,
          },
        });
      }
    },
    handleCellClick(row, column, cell) {
      if (column.property === 'zt' && row.zt === '02') {
        getAssetsBf({ type: 2, pzh: row.pzh }).then(res => {
          if (res.code === 200 && res.data.length > 0) {
            this.$alert(res.data[0].bhyy, '报废驳回原因');
          }
        });
      }
    },
    handleUpdateStatus(row) {
      const params = {
        id: row.kcid,
        zt: '2',
        ztrq: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
      };
      updateKc(params).then(res => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
  .el-card {
    height: 100%;
  }
}
</style>
